// pages/index/index.js
Page({
  data: {
    activeTab: 'all', // 当前选中的标签
    carpoolList: [], // 拼车信息列表
    page: 1, // 当前页码
    pageSize: 10, // 每页数量
    hasMore: true, // 是否还有更多数据
    loading: false // 加载状态
  },

  onLoad: function (options) {
    this.loadCarpoolList();
  },

  // 切换标签
  switchTab: function (e) {
    const tab = e.currentTarget.dataset.tab;
    this.setData({
      activeTab: tab,
      carpoolList: [],
      page: 1,
      hasMore: true
    });
    this.loadCarpoolList();
  },

  // 加载拼车信息列表
  loadCarpoolList: function () {
    if (this.data.loading || !this.data.hasMore) return;

    this.setData({ loading: true });

    const db = wx.cloud.database();
    const collection = db.collection('carpool');

    let query = collection.orderBy('createTime', 'desc');

    // 根据标签筛选
    if (this.data.activeTab !== 'all') {
      query = query.where({
        type: this.data.activeTab
      });
    }

    query.skip((this.data.page - 1) * this.data.pageSize)
      .limit(this.data.pageSize)
      .get()
      .then(res => {
        const newList = res.data.map(item => ({
          ...item,
          createTime: this.formatTime(new Date(item.createTime))
        }));

        this.setData({
          carpoolList: this.data.page === 1 ? newList : [...this.data.carpoolList, ...newList],
          page: this.data.page + 1,
          hasMore: res.data.length === this.data.pageSize,
          loading: false
        });
      })
      .catch(err => {
        console.error('加载拼车信息失败', err);
        wx.showToast({
          title: '加载失败',
          icon: 'error'
        });
        this.setData({ loading: false });
      });
  },

  // 加载更多
  loadMore: function () {
    this.loadCarpoolList();
  },

  // 跳转到详情页
  goToDetail: function (e) {
    const id = e.currentTarget.dataset.id;
    wx.navigateTo({
      url: `/pages/detail/detail?id=${id}`
    });
  },

  // 格式化时间
  formatTime: function (date) {
    const now = new Date();
    const diff = now - date;
    const days = Math.floor(diff / (1000 * 60 * 60 * 24));
    const hours = Math.floor(diff / (1000 * 60 * 60));
    const minutes = Math.floor(diff / (1000 * 60));

    if (days > 0) {
      return `${days}天前`;
    } else if (hours > 0) {
      return `${hours}小时前`;
    } else if (minutes > 0) {
      return `${minutes}分钟前`;
    } else {
      return '刚刚';
    }
  },

  // 下拉刷新
  onPullDownRefresh: function () {
    this.setData({
      carpoolList: [],
      page: 1,
      hasMore: true
    });
    this.loadCarpoolList();
    wx.stopPullDownRefresh();
  },

  // 触底加载更多
  onReachBottom: function () {
    this.loadMore();
  }
});
